import datetime
import inspect
import json


def format_t(frame_dict):
    row = []
    row.append('  File "{}", line {}, in {},index {}\n'.format(
        frame_dict[0], frame_dict[1], frame_dict[2], frame_dict[4]))
    if frame_dict[3]:
        row.append('    {}\n'.format(frame_dict[3][0].strip()))
    return ''.join(row)


def send_user_err(func_name, own_dict):
    from app_main import request_ctx_var
    from app_main import app
    from apps.sql_app.mmongodb import Coll
    request = request_ctx_var.get()
    m = dict()
    if request:
        m["client_ip"] = str(request.client.host)
        m["request_url"] = str(request.url)
        m["request_body"] = str(request.state.mbody)
    m["ip_port"] = app.state.ip + ":" + str(app.state.port)
    m["write_time"] = str(datetime.datetime.now())
    m["func_name"] = func_name
    m["traceback_str"] = ""
    m["args"] = ""
    m["kwargs"] = ""
    m["all_info_dicts"] = json.dumps(own_dict)
    m["client_ip"] = str(request.client.host)
    m["err_source"] = "server"
    m["stack"] = ''.join([format_t(inspect.getframeinfo(i.frame)) for i in inspect.stack()[:10]])
    mongonn = Coll.get_post_user_err()
    mongonn.insert_one(m)